package com.beisita.base.io.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BIOService {

    public static void main(String[] args) {
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(10, 10,
                60L, TimeUnit.SECONDS, new ArrayBlockingQueue(10));
        try (ServerSocket ss = new ServerSocket(6666)) {
            while (true) {
                Socket socket = ss.accept();
                threadPoolExecutor.execute(() -> {
                    handler(socket);
                });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void handler(Socket socket) {

        byte[] bytes = new byte[1024];
        try (InputStream inputStream = socket.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));) {
            int len = 0;
            while ((len = reader.read()) != -1) {
                System.out.print((char) len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
